package com.ruoyi.client.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.client.pojo.form.AddressInsertForm;
import com.ruoyi.client.pojo.form.AddressUpdateForm;
import com.ruoyi.client.pojo.vo.AddressVo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.myshop.domain.Address;

import com.ruoyi.client.service.AddressService;
import com.ruoyi.client.mapper.AddressMapper;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("ClientAddressServiceImpl")
public class AddressServiceImpl implements AddressService {

    @Resource(name = "ClientAddressMapper") //注入指定命名的Bean
    private AddressMapper addressMapper;

    /**
     * 新增收货地址
     */
    @Override
    @Transactional
    public Boolean insert(AddressInsertForm form) {
        //获取登录用户Id
        Long userId = StpUtil.getLoginIdAsLong();

        //数据准备
        Address address = new Address();
        BeanUtils.copyProperties(form, address);
        address.setUserId(userId);
        address.setIsDefault(form.getIsDefault() ? 1 : 0); //数据转换

        Boolean isDefault = address.getIsDefault() != null && address.getIsDefault() > 0;
        if (isDefault) {
            //设置默认地址，需要将原有的默认地址更改掉
            Address defaultAddress = addressMapper.selectDefaultByUserId(address.getUserId());
            if (defaultAddress != null) {
                defaultAddress.setIsDefault(0);  //去掉原有的默认设置
                int updateResult = addressMapper.update(defaultAddress);
                if (updateResult < 1) {
                    //原有的默认地址未更新成功，抛出异常
                    throw new ServiceException("更改默认地址数据库操作错误");
                }
            }
        }
        return addressMapper.insert(address) > 0;
    }

    /**
     * 删除收货地址 ById
     */
    @Override
    public Boolean deleteById(Long addressId) {
        // 用户登录验证,未登录会抛出例外NotLoginException
        StpUtil.checkLogin();
        return addressMapper.deleteByPrimaryKey(addressId) > 0;
    }

    /**
     * 更改收货地址
     */
    @Override
    public Boolean update(AddressUpdateForm form) {

        //获取登录用户Id
        Long userId = StpUtil.getLoginIdAsLong();

        //数据准备
        Address address = new Address();
        BeanUtils.copyProperties(form, address);
        address.setUserId(userId);
        address.setIsDefault(form.getIsDefault() ? 1 : 0); //数据转换

        //处理默认地址，需要将原有的默认地址更改掉
        Address tempAddress = selectByPrimaryKey(address.getId());
        Boolean isDefault = address.getIsDefault() != null && address.getIsDefault() > 0;
        if (isDefault) {
            Address defaultAddress = addressMapper.selectDefaultByUserId(address.getUserId());
            if (defaultAddress != null && tempAddress != null && !defaultAddress.getId().equals(tempAddress.getId())) {
                //存在默认地址且默认地址并不是当前更改的地址
                defaultAddress.setIsDefault(0); //去掉原来的默认地址设置
                int updateResult = addressMapper.update(defaultAddress);
                if (updateResult < 1) {
                    //原默认地址未更新成功，抛出异常
                    throw new ServiceException("更改默认地址数据库操作错误");
                }
            }
        }
        return addressMapper.update(address) > 0;
    }

    /**
     * 查询收货地址ById
     */
    @Override
    public Address selectByPrimaryKey(Long addressId) {
        // 用户登录验证,未登录会抛出例外NotLoginException
        StpUtil.checkLogin();

        Address address = addressMapper.selectByPrimaryKey(addressId);
        if (address == null) {
            throw new ServiceException("id对应的地址不存在");
        }
        return address;
    }

    /**
     * 查询我的收货地址列表
     */
    @Override
    public List<AddressVo> selectListByMy() {
        //获取登录用户Id
        Long userId = StpUtil.getLoginIdAsLong();

        return addressMapper.selectListByUserId(userId);
    }

    /**
     * 查询收货地址详情ById
     */
    @Override
    public AddressVo selectDetailById(Long id) {
        // 用户登录验证,未登录会抛出例外NotLoginException
        StpUtil.checkLogin();

        //查询数据，并检查
        Address address = addressMapper.selectByPrimaryKey(id);
        if (address == null) {
            throw new ServiceException("id对应的地址不存在");
        }
        //数据格式转换，并返回
        AddressVo addressVo = new AddressVo();
        BeanUtils.copyProperties(address, addressVo);
        addressVo.setIsDefault(address.getIsDefault() > 0); //数据转换
        return addressVo;
    }

    // 查询我的默认收货地址，如果传递了id就查询id对应的收货地址，如果没有传递id就查询默认的收货地址
    @Override
    public AddressVo getDefaultAddress(Long addressId) {
        //获取登录用户Id
        Long userId = StpUtil.getLoginIdAsLong();

        Address address;
        if (addressId == null) {
            //参数为空，则返回默认地址;
            address = addressMapper.selectDefaultByUserId(userId);
        } else {
            //参数不为空，则返回id对应的地址
            address = addressMapper.selectByPrimaryKey(addressId);
        }

        if (address == null) {
            throw new ServiceException("默认地址不存在");
        }
        //数据格式转换，并返回
        AddressVo addressVo = new AddressVo();
        BeanUtils.copyProperties(address, addressVo);
        addressVo.setIsDefault(address.getIsDefault() > 0); //数据转换
        return addressVo;
    }

    /**
     * 查询我的默认收货地址
     */
    @Override
    public Address selectDefaultByUserId(Long userId) {
        return addressMapper.selectDefaultByUserId(userId);
    }
}
